"""
行程规划序列化器和视图
"""
from rest_framework import viewsets, serializers, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Itinerary, DayPlan, Activity, ItineraryReminder
from apps.attractions.models import Attraction


class ActivitySerializer(serializers.ModelSerializer):
    """活动序列化器"""
    attraction_name = serializers.CharField(source='attraction.name', read_only=True)
    
    class Meta:
        model = Activity
        fields = '__all__'


class DayPlanSerializer(serializers.ModelSerializer):
    """每日计划序列化器"""
    activities = ActivitySerializer(many=True, read_only=True)
    
    class Meta:
        model = DayPlan
        fields = '__all__'


class ItineraryReminderSerializer(serializers.ModelSerializer):
    """行程提醒序列化器"""
    itinerary_title = serializers.CharField(source='itinerary.title', read_only=True)
    
    class Meta:
        model = ItineraryReminder
        fields = '__all__'
        read_only_fields = ('created_at', 'sent_at')


class ItinerarySerializer(serializers.ModelSerializer):
    """行程序列化器"""
    days = DayPlanSerializer(many=True, read_only=True)
    user_username = serializers.CharField(source='user.username', read_only=True)
    reminders = ItineraryReminderSerializer(many=True, read_only=True)
    
    class Meta:
        model = Itinerary
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')


class ItineraryViewSet(viewsets.ModelViewSet):
    """行程规划视图集"""
    serializer_class = ItinerarySerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return Itinerary.objects.filter(user=self.request.user)
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    
    @action(detail=True, methods=['post'])
    def add_day(self, request, pk=None):
        """添加每日计划"""
        itinerary = self.get_object()
        day_number = request.data.get('day_number')
        date = request.data.get('date')
        
        day_plan = DayPlan.objects.create(
            itinerary=itinerary,
            day_number=day_number,
            date=date
        )
        
        serializer = DayPlanSerializer(day_plan)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    
    @action(detail=True, methods=['post'], url_path='days/(?P<day_id>[^/.]+)/activities')
    def add_activity(self, request, pk=None, day_id=None):
        """添加活动"""
        try:
            day_plan = DayPlan.objects.get(id=day_id, itinerary_id=pk)
        except DayPlan.DoesNotExist:
            return Response({'error': '每日计划不存在'}, status=status.HTTP_404_NOT_FOUND)
        
        activity_data = request.data.copy()
        activity_data['day_plan'] = day_plan.id
        
        serializer = ActivitySerializer(data=activity_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


